package com.yitiao.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yitiao.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        //Sentinel规则的详细信息
        log.info("BlockExceptionHandler BlockException:[{}]",e.getRule().getResource());

        CommonResponse response = null;
        if (e instanceof FlowException) {
            response = new CommonResponse<>(7001,"接口限流");
        } else if (e instanceof DegradeException) {
            response = new CommonResponse<>(7002,"服务降级");
        } else if (e instanceof ParamFlowException) {
            response = new CommonResponse<>(7003,"热点参数限流");
        } else if (e instanceof SystemBlockException) {
            response = new CommonResponse<>(7004,"触发系统保护规则");
        } else if (e instanceof AuthorityException) {
            response = new CommonResponse<>(7005,"授权规则不通过");
            
        }

        //返回json数据
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), response);
    }
}
